import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import getPageTitle from "@/utils/get-page-title";

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async (to, _from, next) => {
  NProgress.start();

  document.title = getPageTitle(to.meta.title);

  const hasGetUserInfo = store.getters.user;
  if (to.meta.auth) {
    // 说明页面需要鉴权
    if (hasGetUserInfo) {
      next();
    } else {
      const hasToken = localStorage.getItem("adminToken");
      if (hasToken) {
        // 验证token有效性
        try {
          await store.dispatch("user/getInfo");
          next();
        } catch (error) {
          await store.dispatch("user/resetToken");
          Message.error("登录过期，请重新登陆");
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      } else {
        next(`/login?redirect=${to.path}`);
        NProgress.done();
      }
    }
  } else {
    // 说明该页面需要鉴权
    if (to.path === "/login" && hasGetUserInfo) {
      next({ path: "/" });
    } else {
      next();
    }
    NProgress.done();
  }
});

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
